package org.groupg.filetodb;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.date.TimeInterval;
import com.lmax.disruptor.RingBuffer;
import com.lmax.disruptor.TimeoutException;
import com.lmax.disruptor.dsl.Disruptor;
import org.apache.commons.dbcp2.BasicDataSource;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.lang3.time.DateUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.io.IOException;
import java.nio.file.Paths;
import java.sql.SQLException;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

public class Demo {
    static final Logger log = LoggerFactory.getLogger(Demo.class.getName());

    public static void main(String[] args) throws IOException, TimeoutException, SQLException {
        TimeInterval timeInterval = new TimeInterval();
        timeInterval.start();
        BasicDataSource dataSource = new BasicDataSource();
        dataSource.setDriverClassName("org.h2.Driver");
        dataSource.setUrl("jdbc:h2:./target/db/filetodb;ifexists=false");
        dataSource.setUsername("SA");
        dataSource.setPassword("");

        String sql = "insert into SYS_USER (ACCOUNT, CNNAME, EMAIL, MOBILE, USERSTATE, ORGCODE, PWD, CREATETIME, CERTTYPE, CERTNO) " +
                " values (?,?,?,?,?,?,?,?,?,?)";

        QueryRunner queryRunner = new QueryRunner(dataSource);
        queryRunner.execute("truncate table sys_user");
        // 1. 初始化Disruptor
        Disruptor<CsvBatchEvent> disruptor = new Disruptor<>(
                CsvBatchEvent::new,
                1024,
                Executors.defaultThreadFactory()
        );

        // 2. 配置处理器
        disruptor.handleEventsWith(new CsvBatchHandler(sql,dataSource));

        // 3. 启动
        RingBuffer<CsvBatchEvent> ringBuffer = disruptor.start();

        // 4. 生产数据
        CsvBatchProducer producer = new CsvBatchProducer(ringBuffer);
        producer.processCsv(Paths.get(new File("E:\\Develops\\demo001-100w.csv").toURI()));

        // 5. 优雅关闭
        disruptor.shutdown(10, TimeUnit.SECONDS);

        log.info("用时：{}", DateUtil.formatBetween(timeInterval.interval()));
        log.info("共处理：{}",CsvBatchHandler.count.get());
    }
}
